package com.mirror.tk.web.controller;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.mirror.tk.framework.common.dao.support.PageInfo;

public class CommonController {

	protected Logger logger = LogManager.getLogger(this.getClass());

	/**
	 * 初始化绑定数据，加入字符串转日期
	 * 自定义string类型转换，防止XSS攻击
	 * 
	 * @param request
	 * @param binder
	 */
	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
		// 时间转换绑定
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(format, true);
		binder.registerCustomEditor(Date.class, dateEditor);
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
		binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
			@Override
			public void setAsText(String text) {
				setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
			}

			@Override
			public String getAsText() {
				Object value = getValue();
				return value != null ? value.toString() : "";
			}
		});
	}

	/**
	 * 分页
	 * 
	 * @param request
	 * @param pageSize
	 * @return
	 */
	protected <T> PageInfo<T> getPageInfo(HttpServletRequest request, int pageSize) {
		int currentPage = 1;
		if (StringUtils.isNotBlank(request.getParameter("pageNo"))) {
			try {
				currentPage = Integer.parseInt(request.getParameter("pageNo"));
			} catch (Exception ex) {
				
			}
		}
		PageInfo<T> pageInfo = new PageInfo<T>(pageSize, currentPage);
		return pageInfo;
	}
	
	/**
	 * 分页
	 * 
	 * @param request
	 * @return
	 */
	protected <T> PageInfo<T> getPageInfo(HttpServletRequest request) {
		return getPageInfo(request, 10);
	}
	
}
